﻿/**
 * Module dependencies.
 */
var express = require('express');
var path = require('path');
var lusca = require('lusca');
var favicon = require('serve-favicon');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var routes = require('./routes/work_overtime');
var userRoutes = require('./routes/work_overtime/UserRoute');
var adminRoutes = require('./routes/work_overtime/adminRoute');
var logger = require('morgan');
var methodOverride = require('method-override');
var errorHandler = require('errorhandler');
var mongoose = require('mongoose');
var app = express();

/** 
 * all environments
 */
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views/work_overtime'));
app.set('view engine', 'jade');

/**
 * 数据库设置
 */
var DB_URL = 'mongodb://localhost:27017/work_overtime';
// 连接
mongoose.connect(DB_URL, { config: { autoIndex: false } });
// 连接成功
mongoose.connection.on('connected', function () {
    console.log('Mongoose connection open to ' + DB_URL);
});
// 连接异常
mongoose.connection.on('error', function (err) {
    console.error('Mongoose connection error: ' + err);
    throw err;
});
// 连接断开
mongoose.connection.on('disconnected', function () {
    console.error('Mongoose connection disconnected');
});



//app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.text());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(methodOverride());
//app.use(cookieParser());
//session env set
app.use(session({
    resave: true,
    saveUninitialized: true,
    secret: 'test sj ps'//,
    //store: new MongoStore({
    //    url: 'mongodb://localhost:27017/mySiteDB',
    //    autoReconnect: true
    //})
}));

//防御csrf和xss攻击
//app.use(function (req, res, next) {
//    if (req.path === '/api/upload') {
//        next();
//    } else {
//        lusca.csrf()(req, res, next);
//    }
//});
//app.use(lusca.xframe('SAMEORIGIN'));
//app.use(lusca.xssProtection(true));
app.use(lusca({
    csrf: true,
    xframe: 'SAMEORIGIN',
    xssProtection: true
}));
app.use(function (req, res, next) {
    res.cookie('x-csrf-token', req.csrf);
    next();
});
//app.get('/', function (req, res) {
//    res.render('index', { title: 'Express', ApplicationName: 'Log查看器', year: new Date().getFullYear() });
//});

app.use(require('stylus').middleware(path.join(__dirname, 'public')));

/**
 * 设置页面模板变量
 */
app.use(function (req, res, next) {    
    res.locals.year = new Date().getFullYear();
    if (req.session.user) {
        res.locals.acc_id = req.session.user._id;
        res.locals.account = req.session.user.account;
        res.locals.emp_name = req.session.user.employee_name;
        res.locals.emp_no = req.session.user.employee_no;
        res.locals.department_name = req.session.user.department_name;
        res.locals.position = req.session.user.position;
    }
    next();
});

app.use('/admin', adminRoutes);
app.use('/user', userRoutes);
app.use('/', routes);

app.use(express.static(path.join(__dirname, 'public')));


/// catch 404 and forwarding to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// development error handler
// will print stacktrace
if ('development' === app.get('env')) {
    app.use(errorHandler());
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

/**
 *Module导出
 */
module.exports = app;